﻿using MbnApi;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Public.Tools
{
    public class Tool
    {
        #region Long Time

        /// <summary>
        /// Long 转 DateTime
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static DateTime LongToDateTime(long unixTimeStamp)
        {
            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
            return dtDateTime;
        }

        /// <summary>
        /// DateTime 转 Long
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long DateTimeToLong(DateTime dateTime)
        {
            DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
            return Convert.ToInt64((dateTime - dtDateTime).TotalMilliseconds);
        }

        #endregion


        #region json exchange obj

        public static string ConvertJsonString(string str)
        {
            //格式化json字符串
            JsonSerializer serializer = new JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 对象转换成json串 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj, bool isConverter = true)
        {
            string json = JsonConvert.SerializeObject(obj);
            return ConvertJsonString(json);

            if (isConverter == true)
                return ConvertJsonString(json);
            else
                return json;
        }

        /// <summary> 
        /// 从一个Json串生成对象信息 
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="jsonString"></param> 
        /// <returns></returns> 
        public static T JsonToObject<T>(string jsonString)
        {
            if (jsonString != "" && jsonString != null)
            {
                return JsonConvert.DeserializeObject<T>(jsonString);
            }
            else
            {
                return default(T);
            }
        }

        #endregion


        #region file

        public static bool Wirte(string file, string content, bool apped = false)
        {
            try
            {
                var paths = file.Split(Path.DirectorySeparatorChar);
                if (paths.Length > 1)
                {
                    var dir = file.Replace(paths[paths.Length - 1], "");
                    if (Directory.Exists(dir) == false)
                        return false;
                }
                using (StreamWriter sw = new StreamWriter(file, apped))
                {
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                Logger.Logger.Error("写入数据失败", ex);
                return false;
            }
        }

        public static Task<bool> WirteAsyn(string file, string content, bool apped = false)
        {
            return Task.Factory.StartNew(() =>
            {
                try
                {
                    DirectoryInfo dir = new DirectoryInfo(file);
                    using (StreamWriter sw = new StreamWriter(file, apped))
                    {
                        sw.Write(content);
                        sw.Flush();
                        sw.Close();
                    }

                    return true;
                }
                catch (Exception ex)
                {
                    Logger.Logger.Error("写入数据失败", ex);
                    return false;
                }
            });
        }

        public static string Read(string file)
        {
            try
            {
                if (File.Exists(file) == false)
                    return null;

                StreamReader streamReader = new StreamReader(file);
                string content = string.Empty;

                while (streamReader.Peek() != -1)
                    content = streamReader.ReadToEnd();
                streamReader.Close();

                return content;
            }
            catch (Exception ex)
            {
                Logger.Logger.Error("读取文件异常 ", ex);
                return null;
            }
        }

        public static List<string> ReadLine(string file)
        {
            try
            {
                if (File.Exists(file) == false)
                    return null;

                var content = File.ReadAllLines(file);
                return content.ToList();
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static bool StreamToFile(Stream stream, string file)
        {
            try
            {
                FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
                byte[] bytes = new byte[1024];
                int num;
                int count = 0;
                do
                {
                    num = stream.Read(bytes, 0, bytes.Length);
                    fs.Write(bytes, 0, num);
                    count += num;
                } while (num > 0);
                fs.Close();
                stream.Close();

                return true;
            }
            catch (Exception ex)
            {
                Logger.Logger.Error("StreamToFile", ex);
                return false;
            }
        }

        #endregion


        #region Image
        /// <summary>
        /// Bitmap图片保存到本地
        /// </summary>
        /// <param name="Img">Bitmap对象</param>
        /// <param name="DirPath">保存图片目录</param>
        /// <param name="ImageName">图片名（不包含格式后缀）</param>
        /// <param name="Format">保存格式</param>
        public static void SaveBitmap(Bitmap img, string filePath, bool isDis = false)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    img.Save(filePath, ImageFormat.Png);
                    if (isDis == true)
                        img.Dispose();
                    return filePath;
                }
                catch (Exception ex)
                {
                    Logger.Logger.Error("保存图片异常", ex);
                    img.Dispose();
                    return null;
                }
            });
        }


        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);



        public static ImageSource ImageConver(Bitmap bitmap)
        {
            try
            {
                IntPtr hBitmap = bitmap.GetHbitmap();
                ImageSource source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    hBitmap,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

                DeleteObject(hBitmap);
                return source;
            }
            catch (Exception ex)
            {
                Logger.Logger.Error("ImageConver 转化异常：", ex);
                return null;
            }
        }

        #endregion


        public static string GetMacAddress()
        {
            List<string> LANMACAddresses = new List<string>();
            string mac = null;
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            if (adapters != null)
            {
                foreach (NetworkInterface ni in adapters)
                {
                    PhysicalAddress pa = ni.GetPhysicalAddress();
                    if (pa == null) continue;
                    string pastr = pa.ToString();
                    if (pastr.Length < 7) continue;
                    if (pastr.Substring(0, 6) == "000000") continue;
                    if (ni.Name.ToLower().IndexOf("vmware") > -1) continue;
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + ni.Id + "\\Connection";
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID     
                        // 如果前面有 PCI 就是本机的真实网卡    
                        // MediaSubType 为 01 则是常见网卡，02为无线网卡。    
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
                            if (ni.NetworkInterfaceType.ToString().ToLower().IndexOf("wireless") == -1)
                                LANMACAddresses.Add(ni.GetPhysicalAddress().ToString());
                    }
                }

                if (LANMACAddresses.Count > 0)
                {
                    mac = LANMACAddresses[0];
                    for (int i = 1; i < LANMACAddresses.Count; i++)
                    {
                        if (mac.CompareTo(LANMACAddresses[i]) == 1)
                            mac = LANMACAddresses[i];  //取最小的那个地址
                    }
                }

            }
            return mac;
        }

        public static string GetWirelessMacAddress()
        {
            List<string> LANMACAddresses = new List<string>();
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            if (null == adapters || 0 == adapters.Length)
            {
                Logger.Logger.Error("本设备未检测到网卡，请检查硬件");
                return null;
            }

            foreach (NetworkInterface ni in adapters)
            {
                if (NetworkInterfaceType.Wwanpp2 != ni.NetworkInterfaceType)
                {
                    continue;
                }

                PhysicalAddress pa = ni.GetPhysicalAddress();
                LANMACAddresses.Add(pa.ToString());
                Logger.Logger.Info($"手机网络网卡有{pa.ToString()}");
            }

            int wirelessCount = LANMACAddresses.Count;
            if (wirelessCount <= 0 || wirelessCount > 1)
            {
                Logger.Logger.Error($"手机网络网卡有{wirelessCount}个，超过了1个，请检查设备信息");
                return null;
            }

            return LANMACAddresses[0];
        }


        public static string GetAppVersion()
        {
            try
            {
                var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ChoJu.Single.exe");
                FileVersionInfo fileVerInfo = FileVersionInfo.GetVersionInfo(file);
                return fileVerInfo.FileVersion;
            }
            catch (Exception ex)
            {
                return "X.X.X.X";
            }
        }

        public static void DirToDir(string sourceDir, string tarDir)
        {
            if (Directory.Exists(sourceDir) == false |
                Directory.Exists(tarDir) == false)
                return;

            var dirs = Directory.GetDirectories(sourceDir);
            if (dirs.Length > 0)
                foreach (var item in dirs)
                    DirToDir(item, tarDir);

            var files = Directory.GetFiles(sourceDir).ToList();
            foreach (var item in files)
            {
                var f = new FileInfo(item);
                DirectoryInfo parent = Directory.GetParent(f.FullName);
                var tarF = Path.Combine(tarDir, parent.Name, f.Name);
                File.Copy(f.FullName, tarF, true);
            }
        }

        /// <summary>
        /// MD5字符串加密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns>加密后字符串</returns>
        public static string GenerateMD5(string txt)
        {
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }

        public static string GenerateMD5(Object obj)
        {
            if (null == obj)
                return "";
            return GenerateMD5(ObjectToJson(obj));
        }

        //获取文件MD5摘要
        public static string GetMD5HashOfFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                using (MD5 md = MD5.Create())
                {
                    FileStream stream = null;
                    try
                    {
                        stream = new FileStream(filePath, FileMode.Open);
                        var bytes = md.ComputeHash(stream);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < bytes.Length; i++)
                        {
                            sb.Append(bytes[i].ToString("x2"));
                        }
                        return sb.ToString();
                    }
                    catch (Exception ex)
                    {
                        return "";
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
            }
            else
                return "";
        }


        public static string Base64UrlEncode(string text)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
            return Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
        }

        /// <summary>  
        /// 根据GUID获取16位的唯一字符串  
        /// </summary>  
        /// <param name=\"guid\"></param>  
        /// <returns></returns>  
        public static string GuidTo16String()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
                i *= ((int)b + 1);
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }

        /// <summary>
        /// 32位GUID字符串
        /// </summary>
        /// <returns></returns>
        public static string GuidTo32String()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }

        public static string GetConfig(string name)
        {
            return ConfigurationManager.AppSettings[name];
        }

        public static long GetHardDiskSpace(string str_HardDiskName)
        {
            long totalSize = new long();
            str_HardDiskName = str_HardDiskName + ":\\";
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    totalSize = drive.TotalSize;
                }
            }
            return totalSize;
        }

        /// <summary> 
        /// 获取指定驱动器的剩余空间总大小(单位为B) 
        /// </summary> 
        /// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param> 
        /// <returns> </returns> 
        public static long GetHardDiskFreeSpace(string str_HardDiskName)
        {
            long freeSpace = new long();
            str_HardDiskName = str_HardDiskName + ":\\";
            DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo drive in drives)
            {
                if (drive.Name == str_HardDiskName)
                {
                    freeSpace = drive.TotalFreeSpace;
                }
            }

            return freeSpace;
        }
        /// <summary>
        /// 删除对应目录下比较旧的文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="removeRate">删除比列</param>
        public static void DeleteOldFile(string path, double removeRate)
        {
            //获取路径下的所有文件
            List<FileInfo> fileInfos = GetAllSubFiles(path);
            //如果没有文件则返回
            if (null == fileInfos || fileInfos.Count <= 0)
                return;

            int fileCount = fileInfos.Count;
            //需要删除的文件数量 = 总文件数量 * 移除比例
            int removeCount = (int)(Math.Floor(fileCount * removeRate));
            //按时间排序，获取文件全路径
            List<string> removeFilePath = fileInfos.OrderBy(f => f.CreationTime).ToList().ConvertAll(f => f.FullName);
            //根据比列从list中移除不需要删除的数据，留在list中的数据则是需要删除的数据
            removeFilePath.RemoveRange(removeCount, fileCount - removeCount);
            Logger.Logger.Info($"====开始自动删除文件,本次删除文件数量为 {removeCount}==== ");
            foreach (string deletePath in removeFilePath)
            {
                File.Delete(deletePath);
            }
        }

        // 功能：获取所给路径文件夹内部的所有子文件，递归。
        // 参数：directoryPath当前处理的文件夹绝对路径，files已获取的子文件们
        // 返回：files 所有子文件绝对路径
        public static List<FileInfo> GetAllSubFiles(string directoryPath, string ext = null)
        {
            if (!Directory.Exists(directoryPath))
                return new List<FileInfo>();
            List<FileInfo> files = new List<FileInfo>();
            DirectoryInfo currentDirectoryInfo = new DirectoryInfo(directoryPath);

            // 当前一级文件夹内的子文件们
            FileInfo[] currentFileInfos = currentDirectoryInfo.GetFiles();
            foreach (FileInfo f in currentFileInfos)
            {
                if (null == ext || ext.ToUpper().Equals(f.Extension.ToUpper()))
                {
                    files.Add(f);
                }
            }

            // 当前一级文件夹内的子文件夹们
            DirectoryInfo[] subDirectoryInfos = currentDirectoryInfo.GetDirectories();
            //递归
            foreach (DirectoryInfo d in subDirectoryInfos)
            {
                files.AddRange(GetAllSubFiles(d.FullName));
            }

            return files;
        }

        /// <summary>
        /// 对比两个对象的属性，并且用新对象不为null的属性的值覆盖老对象的属性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oldObj"></param>
        /// <param name="newObj"></param>
        /// <returns></returns>
        public static T CompareAndSetData<T>(T oldObj, T newObj)
        {
            Type clazz = oldObj.GetType();
            PropertyInfo[] props = clazz.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                Object oldValue = prop.GetValue(oldObj);
                Object newValue = prop.GetValue(newObj);
                //如果旧值和新值为空，那么直接遍历下一个
                if (null == oldValue && null == newValue)
                    continue;

                if (null == oldValue && null != newValue)
                {
                    prop.SetValue(oldObj, newValue);
                    continue;
                }

                if (null != oldValue && null == newValue)
                {
                    prop.SetValue(newObj, oldValue);
                    continue;
                }
                //能走到此步骤的一定是oldValue和newValue都不为null的值
                string oldValueMD5 = GenerateMD5(oldValue);
                string newValueMD5 = GenerateMD5(newValue);
                if (oldValueMD5.Equals(newValueMD5))
                    continue;

                prop.SetValue(oldObj, newValue);
            }

            return oldObj;
        }

        /// <summary>
        /// 把新对象中部位null的值直接复制给老对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oldObj"></param>
        /// <param name="newObj"></param>
        /// <returns></returns>
        public static T OverwiteOldData<T>(T oldObj, T newObj)
        {
            Type clazz = oldObj.GetType();
            PropertyInfo[] props = clazz.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                Object newValue = prop.GetValue(newObj);
                //如果旧值和新值为空，那么直接遍历下一个
                if (null == newValue)
                    continue;

                if (null != newValue)
                    prop.SetValue(oldObj, newValue);
            }

            return oldObj;
        }

        public static byte[] FileToBytes(string Path)
        {
            if (!File.Exists(Path))
            {
                return new byte[0];
            }

            FileInfo fi = new FileInfo(Path);
            byte[] buff = new byte[fi.Length];
            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            return buff;
        }

        public static bool BytesToFile(string path, byte[] data)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(path, FileMode.OpenOrCreate);
                fs.Write(data, 0, data.Length);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Logger.Error("写入文件异常：" + path, ex);
                return false;
            }
            finally
            {
                fs.Close();
            }
        }

        public static void BytesFile(byte[] buff, string savepath)
        {
            if (File.Exists(savepath))
            {
                File.Delete(savepath);
            }

            FileStream fs = new FileStream(savepath, FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(buff, 0, buff.Length);
            fs.Close();
        }

        public static string GetSimIMSI()
        {
            try
            {
                MbnInterfaceManager mbnInfMgr = new MbnInterfaceManager();
                IMbnInterfaceManager infMgr = (IMbnInterfaceManager)mbnInfMgr;
                IMbnInterface[] interfaces = (IMbnInterface[])infMgr.GetInterfaces();
                IMbnSubscriberInformation mbnSubscriberInformation = interfaces[0].GetSubscriberInformation();
                //信号
                //((IMbnSignal)interfaces[0]).GetSignalStrength();
                return mbnSubscriberInformation.SubscriberID;
            }
            catch (Exception ex)
            {
                return "error";
            }
        }

        public static void DirToDirFile(string sourceDir, string tarDir)
        {
            if (Directory.Exists(sourceDir) == false |
                Directory.Exists(tarDir) == false)
                return;

            var files = Directory.GetFiles(sourceDir).ToList();
            foreach (var item in files)
            {
                var f = new FileInfo(item);
                var tarF = Path.Combine(tarDir, f.Name);
                File.Copy(f.FullName, tarF, true);
            }
        }

        public static List<T> DataTableToList<T>(DataTable dt, Dictionary<string, string> dictColumnEN_CN = null, Dictionary<object, object> dictValueRepleace = null) where T : new()
        {
            List<T> list = new List<T>();
            if (dt == null)
            {
                return list;
            }

            Type typeFromHandle = typeof(T);
            string text = "";
            if (dictColumnEN_CN == null)
                dictColumnEN_CN = convertDBNameToClassName(dt.Columns);

            foreach (DataRow row in dt.Rows)
            {
                T val = new T();
                PropertyInfo[] properties = val.GetType().GetProperties();
                PropertyInfo[] array = properties;
                foreach (PropertyInfo propertyInfo in array)
                {
                    try
                    {
                        text = ((dictColumnEN_CN == null || !dictColumnEN_CN.Keys.Contains(propertyInfo.Name)) ? propertyInfo.Name : dictColumnEN_CN[propertyInfo.Name]);
                        if (!dt.Columns.Contains(text) || !propertyInfo.CanWrite)
                        {
                            continue;
                        }

                        object obj = row[text];
                        string text2 = propertyInfo.PropertyType.ToString().ToLower();
                        if (dictValueRepleace != null && dictValueRepleace.Keys.Contains(obj))
                        {
                            obj = dictValueRepleace[obj];
                        }

                        if (obj != DBNull.Value)
                        {
                            if (text2.Contains("int"))
                            {
                                propertyInfo.SetValue(val, int.Parse(obj.ToString()), null);
                            }
                            else if (text2.Contains("long"))
                            {
                                propertyInfo.SetValue(val, long.Parse(obj.ToString()), null);
                            }
                            else if (text2.Contains("decimal"))
                            {
                                propertyInfo.SetValue(val, decimal.Parse(obj.ToString()), null);
                            }
                            else if (text2.Contains("float"))
                            {
                                propertyInfo.SetValue(val, float.Parse(obj.ToString()), null);
                            }
                            else if (text2.Contains("double"))
                            {
                                propertyInfo.SetValue(val, double.Parse(obj.ToString()), null);
                            }
                            else if (text2.Contains("bool"))
                            {
                                propertyInfo.SetValue(val, bool.Parse((obj.ToString() == "1") ? "true" : "false"), null);
                            }
                            else if (text2.Contains("date"))
                            {
                                propertyInfo.SetValue(val, DateTime.Parse(obj.ToString()), null);
                            }
                            else if (propertyInfo.PropertyType.IsEnum)
                            {
                                propertyInfo.SetValue(val, obj, null);
                            }
                            else
                            {
                                propertyInfo.SetValue(val, obj.ToString(), null);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                list.Add(val);
            }

            return list;
        }

        public static Dictionary<string, string> convertDBNameToClassName(DataColumnCollection columns)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            char[] separator = new char[1] { '_' };
            for (int i = 0; i < columns.Count; i++)
            {
                DataColumn dataColumn = columns[i];
                string columnName = dataColumn.ColumnName;
                string[] array = columnName.Split(separator);
                string text = "";
                for (int j = 0; j < array.Length; j++)
                {
                    string slice = array[j];
                    slice = upperCaseFirstChar(slice);
                    text += slice;
                }

                dictionary.Add(text, columnName);
            }

            return dictionary;
        }

        public static string upperCaseFirstChar(string slice)
        {
            if (slice == null || slice.Trim().Length == 0)
            {
                return slice;
            }

            char c = char.ToUpper(slice.ToCharArray()[0]);
            slice = ((slice.Length <= 1) ? char.ToString(c) : (c + slice.Substring(1).ToLower()));
            return slice;
        }

        public static byte[] ConvertToByteArray(object obj)
        {
            if (obj == null)
                return null;

            using (var memoryStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, obj);
                return memoryStream.ToArray();
            }
        }


        #region 

        public static byte[] BitmapToBytes(Bitmap bitmap)
        {
            // 1.先将BitMap转成内存流
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Png);
            ms.Seek(0, SeekOrigin.Begin);
            // 2.再将内存流转成byte[]并返回
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, bytes.Length);
            ms.Dispose();
            return bytes;
        }

        #endregion
    }

    public class HttpMethod
    {
        private bool _isDown = true;

        /// <summary>
        /// GET方式获取数据
        /// </summary>
        public string WebGet(string url, string Token)
        {
            byte[] result = null;
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Token", Token);
            var response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = backStream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            result = new byte[ms.Length];
            result = ms.ToArray();//length=27  709
            return Encoding.UTF8.GetString(result);
        }

        public byte[] ByteWebGet(string url, string Token)
        {
            byte[] result = null;
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Token", Token);
            var response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = backStream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            result = new byte[ms.Length];
            result = ms.ToArray();//length=27  709
            return result;
        }

        /// <summary>
        /// Post方式提交数据，返回网页的源代码
        /// </summary>
        /// <param name="url">发送请求的 URL</param>
        /// <param name="param">请求的参数集合</param>
        /// <returns>远程资源的响应结果</returns>
        public string SendPostJson(string token, string url, string param)
        {
            byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(param.ToString());
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Referer = url;
            request.Method = "POST";
            request.Headers.Add("Token", token);
            request.ContentLength = byteData.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(byteData, 0, byteData.Length);
            stream.Flush();
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            StreamReader resultReader = new StreamReader(backStream, Encoding.UTF8);
            string responseContent = resultReader.ReadToEnd();
            backStream.Close();
            response.Close();
            request.Abort();
            return responseContent;
        }

        public byte[] SendPostProto(string Token, string url, byte[] proto)
        {
            byte[] result = null;

            /*            try
                        {*/
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Token);
            request.ContentType = "application/octet-stream";
            request.Referer = url;
            request.Method = "POST";
            if (proto != null)
            {
                request.ContentLength = proto.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(proto, 0, proto.Length);
                stream.Flush();
                stream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = backStream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            result = new byte[ms.Length];
            result = ms.ToArray();//length=27  709
                                  //StreamReader sr = new StreamReader(backStream, Encoding.Default);
                                  //result = sr.ReadToEnd();               
                                  //sr.Close();
            backStream.Close();
            response.Close();
            request.Abort();
            /*            }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.StackTrace);
                            MessageBox.Show("发生异常1：" + ex.StackTrace, "消息提示");
                            result = null;
                        }*/
            return result;
        }

        public byte[] sendPutProto(string Token, string url, byte[] proto)
        {
            byte[] result = null;

            /*            try
                        {*/
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Token);
            request.ContentType = "application/octet-stream";
            request.Referer = url;
            request.Method = "PUT";
            request.ContentLength = proto.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(proto, 0, proto.Length);
            stream.Flush();
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = backStream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            result = new byte[ms.Length];
            result = ms.ToArray();
            backStream.Close();
            response.Close();
            request.Abort();
            /*            }
                        catch (Exception ex)
                        {
                            string errmsg = ex.Message;
                            MessageBox.Show("发生异常：" + ex.Message, "消息提示");
                            result = null;
                        }*/
            return result;
        }

        /// <summary>   
        /// c#,.net 下载文件      
        /// </summary>       
        /// <param name="URL">下载文件地址</param>    
        ///    
        /// <param name="Filename">下载后的存放地址</param>       
        /// <param name="Prog">用于显示的进度条</param>
        ///       
        public byte[] SendPost(string Token, string url, byte[] proto, string contentType = null)
        {
            byte[] result = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Token", Token);
            request.ContentType = "application/x-protobuf";
            if (!string.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;
            }

            request.Referer = url;
            request.Method = "POST";
            if (proto != null)
            {
                request.ContentLength = proto.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(proto, 0, proto.Length);
                stream.Flush();
                stream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = backStream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            result = new byte[ms.Length];
            result = ms.ToArray();
            backStream.Close();
            response.Close();
            request.Abort();
            return result;
        }

        public byte[] sendPut(string Token, string url, byte[] proto, string contentType = null)
        {
            byte[] result = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Token);
            request.ContentType = "application/x-protobuf";
            if (!string.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;
            }
            request.Referer = url;
            request.Method = "PUT";
            request.ContentLength = proto.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(proto, 0, proto.Length);
            stream.Flush();
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = backStream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            result = new byte[ms.Length];
            result = ms.ToArray();
            backStream.Close();
            response.Close();
            request.Abort();
            return result;
        }

        public byte[] sendPatch(string Token, string url, byte[] proto, string contentType = null)
        {
            byte[] result = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Basic " + Token);
            request.ContentType = "application/x-protobuf";
            if (!string.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;
            }
            request.Referer = url;
            request.Method = "PATCH";
            request.ContentLength = proto.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(proto, 0, proto.Length);
            stream.Flush();
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream backStream = response.GetResponseStream();
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[1024];
            while (true)
            {
                int sz = backStream.Read(buffer, 0, 1024);
                if (sz == 0) break;
                ms.Write(buffer, 0, sz);
            }
            result = new byte[ms.Length];
            result = ms.ToArray();
            backStream.Close();
            response.Close();
            request.Abort();
            return result;
        }


        public void CancelDownlaod()
        {
            _isDown = false;
        }
    }

    public class HttpReqest
    {
        public static string PostBytes(string url, byte[] data)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    // 创建字节数组内容
                    var content = new ByteArrayContent(data);

                    // 设置 Content-Type（根据数据类型修改）
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

                    // 发送 POST 请求
                    HttpResponseMessage response = httpClient.PostAsync(url, content).Result;

                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        string responseBody = response.Content.ReadAsStringAsync().Result;
                        return responseBody;
                    }
                    else
                        return null;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        public static string Get(string url)
        {
            using (var httpClient = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = httpClient.GetAsync(url).Result;

                    // 确保请求成功
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容
                    string responseBody = response.Content.ReadAsStringAsync().Result;
                    return responseBody;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine($"请求错误: {e.Message}");
                    return null;
                }
            }
        }
    }
}
